package com.weyoung.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weyoung.admin.service.FamilyCultureService;
import com.weyoung.admin.mapper.FamilyCultureMapper;
import com.weyoung.admin.service.UserService;
import com.weyoung.common.consatant.exception.ServiceException;
import com.weyoung.common.consatant.result.Result;
import com.weyoung.common.model.entity.FamilyCulture;
import com.weyoung.common.model.entity.UserDO;
import com.weyoung.common.model.vo.app.FamilyCulturesVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.weyoung.common.consatant.errorcode.BaseErrorCode.SERVICE_ERROR;
import static com.weyoung.common.utils.RedisConstants.*;

/**
* @author 27675
* @description 针对表【family_culture(家族文化活动表)】的数据库操作Service实现
* @createDate 2025-04-20 18:27:02
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class FamilyCultureServiceImpl extends ServiceImpl<FamilyCultureMapper, FamilyCulture>
    implements FamilyCultureService{

    private final UserService userService;

    private final StringRedisTemplate stringRedisTemplate;

    private final FamilyCultureMapper familyCultureMapper;

    @Override
    public Result getFamilyCultureListById(String familyId) {
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(FAMILY_CULTURE_LIST_KEY + familyId))){
            // 缓存存在
            String JsonStr = stringRedisTemplate.opsForValue().get(FAMILY_CULTURE_LIST_KEY + familyId);
            log.debug("缓存命中，获取家族文化列表，缓存查询结果：{}", JsonStr);
            // 判断空值
            if (StrUtil.isBlank(JsonStr)){
                // 缓存为空
                return Result.failure("1","未找到对应家族文化记录");
            }
            // 缓存不为空，返回缓存信息
            List<FamilyCulturesVO> list = JSONUtil.toList(JsonStr, FamilyCulturesVO.class);
            return Result.success(list);
        }
        try {
            log.debug("缓存未命中，获取家族文化列表");
            List<FamilyCulturesVO> list = familyCultureMapper.selectCultures(familyId);
            String jsonStr = JSONUtil.toJsonStr(list);
            log.debug("数据库获取家族文化列表，数据库查询结果：{}", jsonStr);
            if (list == null || list.isEmpty()){
                // 数据库未找到
                // 存入空数据入缓存
                stringRedisTemplate.opsForValue().set(FAMILY_CULTURE_LIST_KEY + familyId,
                        "",
                        NULL_EXPIRE_TIME,
                        TimeUnit.MINUTES);
                return Result.failure("1","未找到对应家族文化记录");
            }
            stringRedisTemplate.opsForValue().set(FAMILY_CULTURE_LIST_KEY + familyId,
                    JSONUtil.toJsonStr(list),
                    FAMILY_CULTURE_LIST_EXPIRE_TIME + RandomUtil.randomLong(1, 15),
                    TimeUnit.MINUTES);
            return Result.success(list);
        } catch (Exception e) {
            log.error("获取家族文化列表异常，异常信息: {}", e.getMessage(), e);
            throw new ServiceException("获取家族文化列表异常", e, SERVICE_ERROR);
        }
    }

    @Override
    public Result getFamilyCulture(String cultureId) {
        // 查找缓存是存在
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(FAMILY_CULTURE_KEY + cultureId))){
            // 缓存存在
            String jsonStr = stringRedisTemplate.opsForValue().get(FAMILY_CULTURE_KEY + cultureId);
            log.info("缓存命中，获取家族文化列表，缓存查询结果JsonStr：{}", jsonStr);
            if (StrUtil.isBlank(jsonStr)){
                // 缓存为空
                return Result.failure("1","未找到对应家族文化记录");
            }
            FamilyCulture familyCulture = JSONUtil.toBean(jsonStr, FamilyCulture.class);
            log.info("缓存家族文化列表，数据库查询结果：{}", familyCulture);
            return Result.success(familyCulture);
        }
        // 缓存不存在，查找数据库
        QueryWrapper<FamilyCulture> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("culture_id", cultureId);
        FamilyCulture familyCulture = getOne(queryWrapper);
        // 如果数据库中不存在，返回失败
        if (familyCulture == null){
            stringRedisTemplate.opsForValue().set(FAMILY_CULTURE_KEY + cultureId,
                    "",
                    NULL_EXPIRE_TIME,
                    TimeUnit.MINUTES);
            return Result.failure("1","未找到对应家族文化记录");
        }
        // 数据库存在
        stringRedisTemplate.opsForValue().set(FAMILY_CULTURE_KEY + cultureId,
                JSONUtil.toJsonStr(familyCulture),
                FAMILY_CULTURE_EXPIRE_TIME,
                TimeUnit.MINUTES);
        return Result.success(familyCulture);
    }

    @Override
    public Result deleteFamilyCultureById(String id) {
        // 缓存存在
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(FAMILY_CULTURE_KEY + id))){
            String JsonStr = stringRedisTemplate.opsForValue().get(FAMILY_CULTURE_KEY + id);
            if (StrUtil.isBlank(JsonStr)){
                // 缓存为空
                throw new ServiceException("未找到对应家族文化记录");
            }
            FamilyCulture familyCulture = BeanUtil.toBean(JsonStr, FamilyCulture.class);
            if (familyCultureMapper.deleteCultureById(id)) {
                stringRedisTemplate.delete(FAMILY_CULTURE_KEY + id);
                stringRedisTemplate.delete(FAMILY_CULTURE_LIST_KEY + familyCulture.getFamilyId());
                return Result.success("删除成功");
            }
            throw new ServiceException("删除失败");
        }
        // 缓存不存在，查找数据库
        QueryWrapper<FamilyCulture> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("culture_id", id);
        FamilyCulture familyCulture = getOne(queryWrapper);
        if (familyCulture == null){
            throw new ServiceException("未找到对应家族文化记录");
        }
        if (familyCultureMapper.deleteCultureById(id)) {
            stringRedisTemplate.delete(FAMILY_CULTURE_KEY + id);
            stringRedisTemplate.delete(FAMILY_CULTURE_LIST_KEY + familyCulture.getFamilyId());
            return Result.success("删除成功");
        }
        throw new ServiceException("删除失败");
    }

    /**
     * 获取当前登录用户信息
     * @return 用户实体
     * @throws ServiceException 获取用户失败时抛出
     */
    private UserDO getCurrentUser() {
        try {
            if (!StpUtil.isLogin()) {
                throw new ServiceException("用户未登录");
            }

            Integer userId = Integer.parseInt(StpUtil.getLoginId().toString());
            UserDO user = userService.getById(userId);

            if (user == null) {
                throw new ServiceException("用户不存在");
            }

            if (user.getFamilyId() == null) {
                throw new ServiceException("用户未关联家族");
            }

            return user;
        } catch (Exception e) {
            log.error("获取当前用户信息失败，异常信息: {}", e.getMessage(), e);
            throw new ServiceException("获取用户信息失败", e,SERVICE_ERROR);
        }
    }
}




